package com.lw.web.util;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 操作zookeeper的客户端工具类
 */
public class ZKCurator {

    /**
     * zookeeper 客户端
     */
    private CuratorFramework client = null;

    private Logger log = LoggerFactory.getLogger(ZKCurator.class);

    public ZKCurator(CuratorFramework client){
        this.client = client;
    }

    public void init(){
        client = client.usingNamespace("admin");
        try{
            //判断admin命名空间下面是否有bgm节点  /admin/bgm
            if(client.checkExists().forPath("/bgm")==null){
                client.create().creatingParentsIfNeeded()//递归创建目录
                        /*
                        有两种类型节点：持久节点，临时节点
                        持久节点：创建节点时，节点会永久存在，除非手动删除
                        临时节点：创建节点后，会话断开会自动删除，也可以手动删除
                         */
                        .withMode(CreateMode.PERSISTENT)
                        .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)//acl:匿名权限,不登录即可访问
                        .forPath("/bgm")
                ;
            }
            log.info("zookeeper 初始化成功，启动状态："+client.getState().name());
        }catch (Exception e){
            log.error("",e);
        }
    }

    /**
     * 增加或删除bgm，向zk-server创建子节点，供小程序服务监听
     * @param bgmId
     * @param operType
     */
    public void sendBgmOperator(String bgmId,String operType){
        try{
            String path = "/bgm/"+bgmId;
            //先检查是否存在路径了，如果不存在则创建节点
            if(client.checkExists().forPath(path)==null){
                client.create().withMode(CreateMode.PERSISTENT)
                        .withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE)//acl:匿名权限,不登录即可访问
                        .forPath(path,operType.getBytes());
            }
            //设值
            client.setData().forPath(path, operType.getBytes());

            //删除节点
//            client.delete().forPath(path);

            //递归删除节点及其所有子节点
//            client.delete().deletingChildrenIfNeeded().forPath(path);
        }catch (Exception e){
            log.error("",e);
        }
    }

}
